﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using RentIt06WPFClient.PublisherSession;

namespace RentIt06WPFClient
{
    /// <summary>
    /// Interaction logic for ManageMedia.xaml
    /// </summary>
    public partial class ManageMedia : Page
    {

        public ManageMedia()
        {
            InitializeComponent();
            // Adding a new style as the old one did not have Setters.
            // This could proberbly be done in xaml but it was rather complicated
            // when we use a custom control.
            myMediasList.List.ItemContainerStyle = new Style();
            // Adding a double click event to the list.
            myMediasList.List.ItemContainerStyle.Setters.Add(new EventSetter()
            {
                Event = Control.MouseDoubleClickEvent,
                Handler = new MouseButtonEventHandler(MediaList_MouseDoubleClick)
            });
        }

        private void onCreateNew(object sender, RoutedEventArgs e)
        {
            int newId = Session.Publisher.CreateMedia();
            var newMedia = Session.Publisher.ReadMedia(newId);
            editMedia(newMedia);
        }

        private void onEdit(object sender, RoutedEventArgs e)
        {
            if (myMediasList.SelectedItem != null)
            {
                editMedia((PublisherSession.Media) myMediasList.SelectedItem);
            }
        }

        private void editMedia(PublisherSession.Media media) {
            NavigationService.Navigate(new EditMedia(media));
        }

        private void onUnpublish(object sender, RoutedEventArgs e)
        {
            if (this.myMediasList.SelectedItems.Count <= 0) return;
            if (MessageBox.Show("Are you sure you want to unpublish " + this.myMediasList.SelectedItems.Count + " items?",
                "Unpublish " + this.myMediasList.SelectedItems.Count + " itmes?",
                MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                foreach (PublisherSession.Media media in this.myMediasList.SelectedItems)
                {
                    Session.Publisher.UnPublishMedia(media.Id);
                }
            }
            this.loadPage(sender, e);
        }

        private void MediaList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            this.editMedia((Media)((ListBoxItem)sender).DataContext);
        }

        private void loadPage(object sender, RoutedEventArgs e)
        {
            var mediaList = Session.Publisher.GetMyPublishedMedia();
            myMediasList.ItemsSource = mediaList;
        }
    }
}
